<template>
  <div class="article-container">
    <!--数据表格-->
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="角色列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @emptyQuery="emptyQuery"  @receiveKeyword="receiveKeyword">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('role:insert')">
                <el-button class="toolbar-button" @click="showSaveRoleModal">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增角色
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('role:delete')">
                <el-button class="toolbar-button" @click="batchDelete">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>
          </tool-bar>
          <!--表格-->
          <el-table
            slot="content"
            :data="roleData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectRole"
            @select-all="selectRole"
            :key="tableKey">
            <el-table-column
              type="selection"
              min-width="55"
              :selectable="isNotSuperAdmin"
              align="center">
            </el-table-column>
            <el-table-column
              prop="roleName"
              label="角色名称"
              align="center"
              min-width="50">
            </el-table-column>
            <el-table-column
              prop="description"
              label="角色简介"
              min-width="200">
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="50">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.usable"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  v-if="isNotSuperAdmin(scope.row)"
                  :disabled="!hasPermission('user:update')"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="sort"
              label="排序"
              min-width="30">
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="80">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="100">
              <template slot-scope="scope">
                <span v-if="!hasPermission('role:update')
                  && !hasPermission('role:assignPermission') && !hasPermission('role:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('role:update')"
                  :disabled="!isNotSuperAdmin(scope.row)"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  type="info"
                  size="small"
                  v-if="hasPermission('role:assignPermission')"
                  :disabled="!isNotSuperAdmin(scope.row)"
                  @click="handleAssignPermission(scope.$index, scope.row)">分配权限</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('role:delete')"
                  :disabled="!isNotSuperAdmin(scope.row)"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <!--分页插件-->
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>
    <save-role-template
      :roleDataFromParent="handleCurrentDataForSave"
      @reloadTable="loadDataForRole"
      ref="saveRoleTemplate"></save-role-template>
    <assign-permission-template
      :roleDataFromParent="handleCurrentDataForAssign"
      ref="assignPermissionTemplate"></assign-permission-template>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar';

  import SaveRoleTemplate from "./subView/SaveRoleTemplate";
  import AssignPermissionTemplate from "./subView/AssignPermission";

  import {getRoleByPage, changeUsable, deleteByIds} from "../../network/viewsRequest/role";
  import {hasPermission} from "../../common/permission";

  export default {
    name: 'RoleView',
    data() {
      return {
        query: { // 查询条件都放这里边
          keyword: '',
          currentPage: 1, // 当前页
          pageSize: 10, // 一页显示几条数据
        },
        roleData: [],
        multiSelections: [], // 多选的集合
        total: 0, // 总数据量
        handleCurrentDataForSave: {}, // 传递给保存模态框需要模态框操作的数据
        handleCurrentDataForAssign: {}, // 传递给分配权限模态框操作的数据
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 获取表格中角色的信息
       */
      loadDataForRole() {
        getRoleByPage(this.query).then(res => {
          if (res.code == 1) {
            this.roleData = res.data.items;
            this.total = res.data.total;
          } else {
            this.roleData = [];
            this.total = 0;
          }
        })
      },
      /**
       * 清空查询条件
       */
      emptyQuery() {
        let currentPage = this.query.currentPage;
        let pageSize = this.query.pageSize;
        this.query = {
          keyword: '',
          currentPage: currentPage,
          pageSize: pageSize,
        }
        this.loadDataForRole();
      },
      /**
       * 接受子组件中关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadDataForRole();
      },
      /**
       * 用户点击分页上的页码触发的事件
       */
      getCurrentPageFromPagination() {
        this.query.currentPage = page;
        this.loadDataForRole();
      },
      /**
       * 修改角色的启用状态
       */
      changeUsable(row) {
        // 1.判断该role下面是否有用户，有用户的话不能进行修改
        changeUsable(row.id, row.usable).then(res => {
          if (res.code == 1) {
            this.$message.success("操作成功");
          } else {
            this.$message.error(res.message);
          }
        })

      },
      /**
       * 点击多选框时调用的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectRole(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 点击新增角色时打开的新增用户模态框
       */
      showSaveRoleModal() {
        this.handleCurrentDataForSave = {};
        this.$refs.saveRoleTemplate.show();
      },
      /**
       * 用户点击分配权限调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleAssignPermission(index, row) {
        this.handleCurrentDataForAssign = row;
        this.$refs.assignPermissionTemplate.show();
      },
      /**
       * 用户点击编辑角色信息调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleEdit(index, row) {
        this.handleCurrentDataForSave = row;
        this.$refs.saveRoleTemplate.show();
      },
      /**
       * 用户点击删除角色调用的方法
       * @param index 当前这行数据的索引
       * @param row 当前操作这行数据的内容
       */
      handleDelete(index, row) {
        let delIds = [row.id];
        this.deleteLogic(delIds);
      },
      /**
       * 批量删除角色
       */
      batchDelete() {
        if (this.multiSelections.length == 0) {
          this.$message.error("请选择需要进行删除的角色信息");
          return;
        }
        let delIds = this.multiSelections.map(item => {
          return item.id;
        });
        this.deleteLogic(delIds);
      },
      /**
       * 删除代码的逻辑
       * @param ids 删除的集合
       */
      deleteLogic(ids) {
        this.$confirm("确定要进行删除吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteByIds(ids.join()).then(res => {
            if (res.code == 1) {
              this.$message.success("删除成功！");
              this.loadDataForRole();
            } else {
              this.$message.error(res.message);
            }
          })
        }).catch(() => {
          this.$message.info("删除操作已经被取消");
        })
      },
      /**
       * 本方法是用来判断某行对应的数据是否是超级管理员的，如果是，返回false，即该行不能被选中；反之返回true，即该行能被选中
       * @param row 行数据
       * @param index 行索引
       * @returns {boolean} 如果是，返回false，即该行不能被选中；反之返回true，即该行能被选中
       */
      isNotSuperAdmin(row, index) {
        if (row.roleName == '超级管理员') {
          return false;
        } else {
          return true;
        }
      }
    },
    mounted() {
      this.loadDataForRole();
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.roleData.length; i++) {
          key += this.roleData[i].updateTime;
        }
        return key;
      }
    },
    components: {
      AssignPermissionTemplate,
      SaveRoleTemplate,
      Card,
      Pagination,
      ToolBar,
    }
  }
</script>

<style scoped>

  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block !important;
    vertical-align: bottom;
    position: relative;
  }
  .button-all-container {
    display: inline-block;
    vertical-align: bottom;
  }

  .custom-container {
    display: inline-block;
    margin-left: 10px
  }

  .el-card {
    margin-top: 30px;
  }

  .el-select {
    width: 110px;
  }
  .btn-container {
    margin-right: 5px;
  }

  .category-select {
    margin-right: 5px;
  }

</style>

<style>

  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 12px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-input--small .el-input__inner {
    height: 36px;
  }

  .el-select-dropdown__wrap, .el-scrollbar__wrap {
    margin-bottom: 0px !important
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
